package com.funsport.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.funsport.entity.CommunityPost;
import com.funsport.entity.PostLike;
import com.funsport.mapper.CommunityPostMapper;
import com.funsport.mapper.PostLikeMapper;
import com.funsport.service.ICommunityPostService;
import com.funsport.service.IPointsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * CommunityPost Service实现
 */
@Slf4j
@Service
public class CommunityPostServiceImpl extends ServiceImpl<CommunityPostMapper, CommunityPost> implements ICommunityPostService {

    @Autowired
    private PostLikeMapper postLikeMapper;
    
    @Lazy
    @Autowired
    private IPointsService pointsService;

    @Override
    @Transactional
    public boolean toggleLike(Long postId, Long userId) {
        try {
            // 检查是否已经点赞
            LambdaQueryWrapper<PostLike> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(PostLike::getPostId, postId)
                   .eq(PostLike::getUserId, userId);
            
            PostLike existingLike = postLikeMapper.selectOne(wrapper);
            
            CommunityPost post = this.getById(postId);
            if (post == null) {
                log.warn("帖子不存在: postId={}", postId);
                return false;
            }
            
            if (existingLike != null) {
                // 已点赞，取消点赞
                postLikeMapper.deleteById(existingLike.getId());
                
                // 减少点赞数
                int newLikeCount = Math.max(0, post.getLikeCount() - 1);
                post.setLikeCount(newLikeCount);
                this.updateById(post);
                
                log.info("取消点赞成功: postId={}, userId={}", postId, userId);
                // 取消点赞不扣除积分
            } else {
                // 未点赞，添加点赞
                PostLike newLike = new PostLike();
                newLike.setPostId(postId);
                newLike.setUserId(userId);
                postLikeMapper.insert(newLike);
                
                // 增加点赞数
                post.setLikeCount(post.getLikeCount() + 1);
                this.updateById(post);
                
                log.info("点赞成功: postId={}, userId={}", postId, userId);
                
                // 奖励帖子作者积分（不能给自己点赞获得积分）
                if (!post.getAuthorId().equals(userId)) {
                    try {
                        pointsService.addUserPoints(post.getAuthorId(), 3, "帖子被点赞", null, null);
                        log.info("帖子被点赞奖励积分: postOwnerId={}, postId={}, likerId={}", 
                            post.getAuthorId(), postId, userId);
                    } catch (Exception e) {
                        log.error("帖子被点赞奖励积分失败: postOwnerId={}, postId={}, likerId={}", 
                            post.getAuthorId(), postId, userId, e);
                    }
                }
            }
            
            return true;
            
        } catch (Exception e) {
            log.error("点赞操作失败: postId={}, userId={}", postId, userId, e);
            return false;
        }
    }
}
